# -*-coding:utf-8-*-
import os

import chardet
import time
from numpy import unicode

from common import config
from common import sqlite
from common import localdisk
from common import wenjin_api

__author__ = 'Jason'

# processedDir是处理完的图书存放的地方
def build(dir,dest_dir,processedDir = config.processedDir,qDocType="图书"):
    files = []
    fielnum =0
    cates = sqlite.loadBookCategroy(config.getMainDb())
    list = os.listdir(dir)#列出目录下的所有文件和目录
    for line in list:
        filepath = os.path.join(dir,line) # .decode('gbk', 'ignore').encode('utf-8')
        print(filepath)
        if os.path.isdir(filepath):#如果filepath是目录，则再列出该目录下的所有文件
            build(filepath,dest_dir,processedDir)
            """for li in os.listdir(filepath):
                files.append(filepath)
                fielnum = fielnum + 1"""
        elif os.path:#如果filepath是文件，直接列出文件名
            files.append(filepath)
            (title,extName) = getTitle(filepath)

            if extName == "pdf":
                if "恒星与行星" in title:
                    book.summary = "OK"

                book = wenjin_api.query(title,qDocType)
                if book.sort_no :
                    print("-----{0}-----".format(book.sort_no))
                    dirPath = ""
                    try:
                         dirPath = localdisk.createBookDir(cates,dest_dir,book.sort_no)
                    except Exception as e:
                        print(e)
                        print("--分类信息错误--{0}--{1}".format(dest_dir, book.sort_no))
                        result = False

                    if dirPath:
                        print("-----OK-----")
                        localdisk.copyFile(filepath,dirPath)
                        localdisk.moveFile(filepath,processedDir + "\\" + time.strftime("%Y-%m-%d"))

            print(filepath)
            fielnum = fielnum + 1

    print('文件数: '+ str(fielnum))
    return  files

def getTitle(filePath):
    filename = os.path.basename(filePath)
    pos = filename.rfind(".")
    title = filename[0:pos]
    extName = filename[pos+1:].lower()

    return (title,extName)

def fixString(ustring):
    codedetect = chardet.detect(ustring)["encoding"]
    # 将编码codedetect转成unicode
    ustring = unicode(ustring, codedetect)
    # 将unicode编码成utf - 8
    return ustring.encode("utf-8")